﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public interface ICandidatesListPanel
{
    void OnSelectCandidate(long candidateId);
    void OnConfirm(long candidateId);
    void OnBuy();
}
public class CandidatesListPanel : PanelCommon
{
    public ICandidatesListPanel uiListener { get; set; }

    List<CandidatesItem> m_Items = new List<CandidatesItem>();

    public Transform itemsParent;
    public CandidatesItem skinsItemPref;

    public GameObject buyBtn;

    public override void Awake()
    {
        base.Awake();

        skinsItemPref.gameObject.SetActive(false);
    }

    public void Init(CandidatesListVCData data)
    {
        for (int i = 0; i < data.candidates.Count; i++)
        {
            var newItem = Instantiate(skinsItemPref, itemsParent);
            newItem.gameObject.SetActive(true);
            newItem.Init(data.candidates[i], OnSelectItem, OnConfirm);

            m_Items.Add(newItem);
        }

        var ild = GetComponentInChildren<ItemListDispersed>();
        if (ild)
        {
            ild.maxIndex = m_Items.Count - 1;
        }
        OnSelectItem(m_Items.Find(e => e.Id == data.defaultCandidate));
       
        m_ToHide = false;
    }

    public void OnBuy()
    {
        uiListener?.OnBuy();
    }

    public void OnConfirm(CandidatesItem candidate)
    {
        this.uiListener?.OnConfirm(candidate.Id);
    }

    void OnSelectItem(CandidatesItem skinsItem)
    {
        if (!skinsItem)
            return;

        this.uiListener?.OnSelectCandidate(skinsItem.Id);

        this.buyBtn.SetActive(!skinsItem.unlock);

        foreach (var item in m_Items)
        {
            if(item == skinsItem)
                item.selectSign.gameObject.SetActive(true);
            else
                item.selectSign.gameObject.SetActive(false);
        }
    }

    protected override void GoBackToView()
    {
        base.GoBackToView();
        
        GoBackToBattleUI();
    }

    bool m_ToHide;

    void GoBackToBattleUI()
    {
        if (m_ToHide)
            return;

        m_ToHide = true;

        //this.m_Controller.parentNav.LoadDisplay<MBattleUIViewController>();
        GetComponentInParent<MBattleSceneController>().ShowBattleUI();
    }

    internal void UpdateCandidate(CandidateVCData data)
    {
        var item = this.m_Items.Find(e => e.Id == data.candidateId);
        if (item)
        {
            item.UpdateCandidate(data);

            this.buyBtn.SetActive(!item.unlock);
        }

        this.buyBtn.SetActive(!data.unlock);
    }

    public void RefreshMsg(int id, int result,string refuseReason = "")
    {
        this.m_Items.Find(e => e.Id == id).RefreshMsg(result,refuseReason);
    }
}
